import React from 'react';
import { Button, Drawer, Space, Spin } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';
import { connect } from 'umi';

import { LineChartOutlined, UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components/index.js';
import { TjTable, useTRState } from '@/pages/ETrade/components';
import { useExcel } from '@/hooks';

import { default as HeadForm } from './form';
import { default as DrawerCharts } from './charts';
import { getSettlementAnalyse, queryMarketList } from './services.js';
import { getColumns } from './helper';
import styles from './index.less';
import { getTreeByCodes } from '@/utils';

const exportKey = 'MedLongTermSettlementAnalyseExport';
const MidSettlementAnalysis = ({ menuCode, buttonPermissions }) => {
  /** data */
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 数据
    formValues: null,
    loading: true,
    tableData: [],
    tableColumns: [],
    showDrawer: false,
  });

  React.useEffect(() => {
    init();
  }, []);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryMarketList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      // tree需要唯一值键，处理一下
      power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
  };

  const fetch = async (values) => {
    // 数据
    if (!values || !values?.contractIdList?.length) {
      return setState({
        tableData: [],
        loading: false,
      });
    }
    setState({ loading: true });
    const res = await getSettlementAnalyse(values);
    const tableColumns = getColumns(res?.dataHead);
    const tableData = [...(res?.totalList || []), ...(res?.formBodyList || [])];
    setState({
      tableColumns,
      tableData,
      loading: false,
    });
  };

  /** methods */
  const onChangeForm = (values) => {
    // 查询
    setState({ formValues: values });
    fetch(values);
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return Message.info('请联系管理员获取相关权限');
    let exportData = [];
    state.tableData.map(({ children, ...x }) => {
      exportData.push(x);
      if (!!children?.length) {
        exportData = exportData.concat(children);
      }
    });
    useExcel({
      filename: `中长期结算分析`,
      columns: state.tableColumns,
      data: exportData,
      merges: ['contractName', 'contractElectricQuantity', 'contractElectricPrice'],
    });
  };

  /** render */
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: state.tableData, columns: state.tableColumns })
    .primaryKey('tableId')
    .use(features.rowGrouping({ defaultOpenAll: true }))
    .use(features.autoRowSpan())
    .appendRowPropsGetter((record, rowIndex) => {
      const hasBg = !!record.children || rowIndex === 0 || rowIndex === 1;
      const color = hasBg ? '#2D3133' : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return (
      <div className={styles.box}>
        <div className={styles.title}>
          <div>中长期结算分析</div>
          <Space size={16}>
            <Button
              disabled={state.loading || !state.formValues}
              style={{ padding: 0 }}
              type="link"
              icon={<LineChartOutlined />}
              onClick={() => setState({ showDrawer: true })}
            >
              图形分析
            </Button>
            <Button
              disabled={state.loading}
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.table}>
          <TjTable {...pipeline.getProps()} useVirtual={false} />
        </div>

        {/* <TjChart option={state.charts?.[0]} group={menuCode} /> */}
      </div>
    );
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.container}>
        <div className={styles.head}>
          <HeadForm power={state.power} onChange={onChangeForm} />
        </div>
        <div className={styles.main}>{_renderMain()}</div>
        {!!state.showDrawer && (
          <Drawer
            className={'tj_drawer'}
            visible={state.showDrawer}
            title={'图形分析'}
            width={'73%'}
            placement={'right'}
            destroyOnClose={true}
            getContainer={false}
            onClose={() => setState({ showDrawer: false })}
          >
            <DrawerCharts params={state.formValues} />
          </Drawer>
        )}
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(MidSettlementAnalysis);
